<?php

namespace App\Admin\Controllers;


use App\Models\TemplateMessage;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\WeChat\WxTrait;
use Encore\Admin\Widgets\Table;


class TemplateMessageController extends Controller
{
    use ModelForm;
    use WxTrait;
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('通知消息');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('通知消息');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('通知消息');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Admin::script($this->script());
        return Admin::grid(TemplateMessage::class, function (Grid $grid) {
            $grid->actions(function ($actions) {
                $row = $actions->row;
                if ($row->have_send == 0) {
                    $actions->prepend('<a href="' . url('admin/sendMessage/' . $row->id) . '"><i class="fa fa-paper-plane"></i></a>');
                }
            });
            $grid->id("ID")->sortable();
            $grid->openid('用户名')->display(function ($data) {
                $nickname = User::where('openid', $data)->value('nickname');
                return deal_emoji($nickname);
            });
            $grid->title('标题');
            $grid->url('链接');
            $grid->have_send('是否发送')->display(function ($data) {
                return $data ? '是' : '否';
            });
            $grid->msgid('msgid');
            $grid->errcode('errcode');
            $grid->errmsg('errmsg');
            $grid->created_at('创建时间');
            $grid->updated_at('更新时间');
            $grid->more('内容')->display(function () {
                $content=var_export(json_decode($this->content,true),true);
                $rows = [
                    ['内容', $content],
                ];
                $table = new Table([], $rows);
                return <<<DATA
<a class="btn btn-xs btn-default grid-expand" data-inserted="0" data-key="{$this->id}" 
data-toggle="collapse" data-target="#grid-collapse-{$this->id}">
    <i class="fa fa-caret-right"></i> 详情
</a>
<template class="grid-expand-{$this->id}">
    <div id="grid-collapse-{$this->id}" class="collapse">
   {$table}
</div>
</template>
DATA;
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(TemplateMessage::class, function (Form $form) {

            $form->text('openid','openid');
            $form->text('title','标题');
            $form->text('content','内容');
            $form->url('url','链接');
            $form->radio('have_send','是否已发送')->options(['0' => '未发送', '1'=> '已发送'])->default('0');
            $form->text('template_id','模板消息id');
            $form->display('msgid','msgid');
            $form->display('errcode','errcode');
            $form->display('errmsg','errmsg');
        });
    }

    /**
     * 名称：发送模板消息
     * 必要条件：
     * 功能：
     * 任务：
     */
    public function sendMessage($id)
    {
        $res=$this->sendTemplateMessage($id);
        if($res['result']){
            $success = new MessageBag([
                'title'   => '发送成功',
                'message' => $res['message'],
            ]);
            return back()->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title'   => '发送失败',
                'message' => $res['message'],
            ]);
            return back()->with(compact('error'));
        }
    }

    protected function script()
    {
        return <<<SCRIPT
$('.grid-expand').on('click', function () {
     if ($(this).data('inserted') == '0') {
        var key = $(this).data('key');
        var row = $(this).closest('tr');
        var html = $('template.grid-expand-'+key).html();

        row.after("<tr><td colspan='"+row.find('td').length+"' style='padding:0 !important; border:0px;'>"+html+"</td></tr>");

        $(this).data('inserted', 1);
    }

    $("i", this).toggleClass("fa-caret-right fa-caret-down");

});

SCRIPT;
    }
}
